package ink.sunflower.aclservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import ink.sunflower.aclservice.entity.User;
import ink.sunflower.aclservice.service.PermissionService;
import ink.sunflower.aclservice.service.UserService;
import ink.sunflower.security.entity.SecurityUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zhaokuii11@163.com
 * @create 2022-06-06 22:48
 * @Description
 */
@Service("userDetailsService") //根据名字进行注入
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    UserService userService;
    @Autowired
    PermissionService permissionService;

    /**
     * 根据用户名查询数据库，返回security要求的对象
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询数据ku
        User user = userService.selectByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        ink.sunflower.security.entity.User curUser =
                new ink.sunflower.security.entity.User();
        BeanUtils.copyProperties(user, curUser);
        //根据用户查询用户权限列表
        List<String> permissionList =
                permissionService.selectPermissionValueByUserId(user.getId());

        SecurityUser securityUser = new SecurityUser();
        securityUser.setPermissionValueList(permissionList);
        securityUser.setCurrentUserInfo(curUser);
        return securityUser;
    }
}
